const app = require("express").Router();
const { Address } = require("../model/index");

app.get("/getaddress", (req, res) => {
  Address.findAndCountAll({
    where: {
      userid: req.query.userid,
    },
  }).then((ret) => {
    if (ret) {
      res.send({ code: 0, data: ret });
    } else {
      res.send({ code: -1, msg: "获取地址失败" });
    }
  });
});

app.post("/addaddress", (req, res) => {
  Address.create(req.body).then((ret) => {
    if (ret) {
      res.send({ code: 0, data: ret });
    } else {
      res.send({ code: -1, msg: "添加失败" });
    }
  }).catch(err=>{
    res.send({ code: -1, msg: err });
  })
});

app.post("/updateaddress", (req, res) => {
  Address.update(req.body, {
    where: {
      userid: req.body.userid,
      id: req.body.id,
    },
  }).then((ret) => {
    if (ret) {
      res.send({ code: 0, data: ret });
    } else {
      res.send({ code: -1, msg: "编辑失败" });
    }
  });
});

app.get("/deladdress", (req, res) => {
  Address.destroy({
    where: {
      userid: req.query.userid,
      id: req.query.id,
    },
  }).then((ret) => {
    if (ret) {
      res.send({ code: 0, data: ret });
    } else {
      res.send({ code: -1, msg: "删除失败" });
    }
  });
});

module.exports = app